package com.example.jones.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.example.constant.AppConstant;
import com.example.constant.MessageType;
import com.example.constant.VariableKey;
import com.example.util.ApkInstaller;
import com.example.util.CookbookImage;
import com.example.util.HttpUtil;
import com.example.util.HttpUtilWithParameter;
import com.example.util.JsonParser;
import com.example.util.NumberUtils;
import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.RecognizerListener;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechConstant;
import com.iflytek.speech.SpeechRecognizer;
import com.iflytek.speech.SpeechSynthesizer;
import com.iflytek.speech.SpeechUtility;
import com.iflytek.speech.SynthesizerListener;

@SuppressLint({ "HandlerLeak", "ShowToast" })
public class DtlActivity extends Activity {

    private DtlAdepter dat;
    private ListView lv_list, staple_food_list, ingredient_list;
    private ImageView lv_play, lv_t1, lv_t2, lv_t3, cbImage;
    private TextView tv_dtl, t1;
    private boolean flag = true;

    private String cbID = "1";
    private String dishImage, dishName;
    private List<Map<String, Object>> list_Staple = new ArrayList<Map<String, Object>>();
    private List<Map<String, Object>> list_Ingredient = new ArrayList<Map<String, Object>>();
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    // 语音合成
    private SpeechSynthesizer speechSynthesizer;
    // 语音识别
    private SpeechRecognizer speechRecognizer;

    private Toast mToast;

    private int stepNum = 0;
    private String orderPrevStep;
    private String orderNextStep;
    private String orderPause;
    private String orderRePlay;
    private int whichPlay = 0;
    private boolean isPause = false;
    private String tips = "";
    private String pauseTimeStr = "五秒";
    private long pauseTimeValue = AppConstant.PAUSE_DELAY;

    private MediaPlayer mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);

        Intent it = super.getIntent();
        cbID = it.getStringExtra("cbID");
        dishImage = it.getStringExtra("dishImage");
        dishName = it.getStringExtra("dishName");

        orderPrevStep = getString(R.string.order_prev_step);
        orderNextStep = getString(R.string.order_next_step);
        orderPause = getString(R.string.order_pause);
        orderRePlay = getString(R.string.order_replay);
        mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);

        // 初始化语音合成
        speechSynthesizer = new SpeechSynthesizer(DtlActivity.this,
                new InitListener() {

                    @Override
                    public void onInit(ISpeechModule arg0, int arg1) {
                        if (arg1 != ErrorCode.SUCCESS) {
                            showTip("语音服务异常");
                        }
                    }
                });

        // 初始化语音识别
        speechRecognizer = new SpeechRecognizer(DtlActivity.this,
                new InitListener() {

                    @Override
                    public void onInit(ISpeechModule arg0, int arg1) {
                        if (arg1 != ErrorCode.SUCCESS) {
                            showTip("语音服务异常");
                        }
                    }
                });

        lv_list = (ListView) this.findViewById(R.id.lv_list); // 做法步骤
        staple_food_list = (ListView) this.findViewById(R.id.staple_food_list); // 主料
        ingredient_list = (ListView) this.findViewById(R.id.ingredient_list); // 主料

        lv_t1 = (ImageView) this.findViewById(R.id.lv_t1); // 收藏按鈕圖片
        lv_t2 = (ImageView) this.findViewById(R.id.lv_t2); // 分享按鈕圖片
        lv_t3 = (ImageView) this.findViewById(R.id.lv_t3); // 更多按钮图片
        lv_play = (ImageView) this.findViewById(R.id.lv_play); // 播放按钮图片
        tv_dtl = (TextView) this.findViewById(R.id.tv_dtl); // 购物清单
        t1 = (TextView) this.findViewById(R.id.t1); // 菜谱名
        cbImage = (ImageView) this.findViewById(R.id.cbImage); // 菜谱效果图

        CookbookImage cbimg = new CookbookImage();
        cbImage.setImageBitmap(cbimg.getmybitmap(dishImage)); // 设置菜谱的图片
        t1.setText(dishName);

        // 主料取值
        try {
            String staple_food_url = HttpUtil.Base_url + "/CookMaterialService";
            JSONArray staple_food_jsonArray = new JSONArray(
                    HttpUtilWithParameter.getCookMethod(staple_food_url, cbID));
            System.out.println("###staple_food_jsonArray"
                    + staple_food_jsonArray);

            for (int i = 0; i < staple_food_jsonArray.length(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject obj = staple_food_jsonArray.getJSONObject(i);
                map.put("name", obj.get("name"));
                map.put("amount", obj.get("amount"));
                if (obj.get("type").equals("主料")) {
                    list_Staple.add(map);
                } else {
                    list_Ingredient.add(map);
                }
            }

            SimpleAdapter simpleAdapter_Staple = new SimpleAdapter(this,
                    list_Staple, R.layout.staple_food_list, new String[] {
                            "name", "amount" }, new int[] { R.id.material_name,
                            R.id.material_amount });
            staple_food_list.setAdapter(simpleAdapter_Staple);
            setListViewHeightBasedOnChildren(staple_food_list);

            SimpleAdapter simpleAdapter_Ingredient = new SimpleAdapter(this,
                    list_Ingredient, R.layout.staple_food_list, new String[] {
                            "name", "amount" }, new int[] { R.id.material_name,
                            R.id.material_amount });
            ingredient_list.setAdapter(simpleAdapter_Ingredient);
            setListViewHeightBasedOnChildren(ingredient_list);

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // String dtl_url=HttpUtil.Base_url+"/CookMethodService";
        // JSONArray dtljsonArray;
        // try {
        // dtljsonArray = new
        // JSONArray(HttpUtilWithParameter.getCookMethod(dtl_url,cbID));
        // dat = new DtlAdepter(dtljsonArray);
        // lv_list.setAdapter(dat);
        // setListViewHeightBasedOnChildren(lv_list);
        // } catch (JSONException e) {
        // e.printStackTrace();
        // }

        // 做法步驟的取值
        try {
            String dtl_url = HttpUtil.Base_url + "/CookMethodService";
            JSONArray dtljsonArray = new JSONArray(
                    HttpUtilWithParameter.getCookMethod(dtl_url, cbID));
            System.out.println("###dtljsonArray" + dtljsonArray);

            for (int i = 0; i < dtljsonArray.length(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject obj = dtljsonArray.getJSONObject(i);

                map.put("content", obj.get("content"));
                map.put("NO", obj.get("NO"));

                if (null == obj.get("pic")) {
                } else {
                    CookbookImage cbimg1 = new CookbookImage();
                    System.out.println("###pic.name)"
                            + obj.get("pic").toString());
                    Bitmap bm = cbimg1.getmybitmap(obj.get("pic").toString());
                    map.put("pic", bm);
                }
                list.add(map);
            }

            SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
                    R.layout.dtl_list_item, new String[] { "content", "NO",
                            "pic" }, new int[] { R.id.dt_list_step,
                            R.id.dt_list_count, R.id.iv_center });

            simpleAdapter.setViewBinder(new ViewBinder() {
                @Override
                public boolean setViewValue(View view, Object data,
                        String textRepresentation) {
                    if (view instanceof ImageView && data instanceof Bitmap) {
                        ((ImageView) view).setImageBitmap((Bitmap) data);
                        return true;
                    }
                    return false;
                }
            });

            lv_list.setAdapter(simpleAdapter);
            setListViewHeightBasedOnChildren(lv_list);

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        lv_play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                installGuide();
                if (flag) {
                    lv_play.setBackgroundResource(R.drawable.pic_arrow_right);
                    flag = false;
                    isPause = false;
                    speechSynthesizer.setParameter(SpeechConstant.ENGINE_TYPE,
                            "local");
                    speechSynthesizer.setParameter(
                            SpeechSynthesizer.VOICE_NAME, "xiaoyan");
                    speechSynthesizer.setParameter(SpeechSynthesizer.SPEED,
                            "50");
                    speechSynthesizer.setParameter(SpeechSynthesizer.PITCH,
                            "50");

                    whichPlay = 1;
                    mHandler.sendEmptyMessage(MessageType.SYNTHESIZE_STEP);

                } else {
                    lv_play.setBackgroundResource(R.drawable.open_icon);
                    flag = true;
                    whichPlay = 5;
                    isPause = true;
                    speechSynthesizer.stopSpeaking(synthesizerListener);
                    speechRecognizer.stopListening(recognizerListener);
                }
            }
        });

        lv_t1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String url = HttpUtil.Base_url + "/CollectionService";
                if (!AppConstant.GLOBAL_VARIABLE
                        .containsKey(VariableKey.USER_ID)) {
                    showTip("收藏失败，你还未登录");
                    return;
                }
                if (HttpUtilWithParameter.collecte(url,
                        (String) AppConstant.GLOBAL_VARIABLE
                                .get(VariableKey.USER_ID), cbID)) {
                    showTip("收藏成功");

                } else {
                    showTip("收藏失败");
                }
            }
        });

        lv_t2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
            	// TODO caipu
            	doCpShare();
            }
        });

        lv_t3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Toast.makeText(DtlActivity.this, "点击了按钮3！", 1000).show();
            }
        });

        tv_dtl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast.makeText(DtlActivity.this, "查看清单！", 1000).show();
            }
        });

    }
    
    /**
     * 菜谱分享
     */
    private void doCpShare(){
    	String sharmsg = "我给大家分享\"" + t1.getText().toString() + "\"的做法，还有语音指导，下载语音菜谱获取更多菜谱" + HttpUtil.Base_url + "/download/Cp_test.apk";
    	 Intent intent=new Intent(Intent.ACTION_SEND);
         
         intent.setType("text/plain");
         intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
         intent.putExtra(Intent.EXTRA_TEXT, sharmsg);
         startActivity(Intent.createChooser(intent, getTitle()));
         
         new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
				    HttpPost post = new HttpPost(HttpUtil.Base_url + "/ShareCookbookService" );
				    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
				    NameValuePair pair1 = new BasicNameValuePair("cbID",cbID);
				    pairs.add(pair1);
				    HttpEntity entity = new UrlEncodedFormEntity(pairs,"UTF-8");//设置编码，防止中文乱码
				    post.setEntity(entity);
				    new DefaultHttpClient().execute(post);
				    } catch (Exception e) {
						Log.e("bad", e.getMessage());
					} 
			}
		}).start();
    }

    /**
     * 事件调度器
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int code = 0;
            switch (msg.what) {
            case MessageType.CHANGE_ICON_PLAY: // 改变图标为播放状态
                lv_play.setBackgroundResource(R.drawable.open_icon);
                break;
            case MessageType.SYNTHESIZE_STEP: // 播放步骤
                code = speechSynthesizer.startSpeaking(
                        (String) list.get(stepNum).get("content"),
                        synthesizerListener);
                if (ErrorCode.SUCCESS != code) {
                    showTip(getString(R.string.play_fail));
                }
                break;
            case MessageType.SYNTHESIZE_TIP: // 播放提示
                code = speechSynthesizer.startSpeaking(tips,
                        synthesizerListener);
                if (ErrorCode.SUCCESS != code) {
                    showTip(getString(R.string.play_fail));
                }
                break;
            case MessageType.RECOGNIZE: // 语音识别
                code = speechRecognizer.startListening(recognizerListener);
                if (ErrorCode.SUCCESS != code) {
                    showTip(getString(R.string.order_fail));
                }
                break;

            default:
                break;
            }
        }
    };

    /**
     * 讯飞安装引导
     */
    private void installGuide() {
        // 没有可用的语音引擎，则引导安装讯飞语音服务
        if (SpeechUtility.getUtility(DtlActivity.this).queryAvailableEngines() == null
                || SpeechUtility.getUtility(DtlActivity.this)
                        .queryAvailableEngines().length <= 0) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(
                    DtlActivity.this);
            dialog.setMessage(getString(R.string.install_confirm_msg));
            dialog.setNegativeButton(R.string.install_cancel_button, null);
            dialog.setPositiveButton(
                    getString(R.string.install_confirm_button),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface,
                                int i) {
                            String url = SpeechUtility.getUtility(
                                    DtlActivity.this).getComponentUrl();
                            processInstall(DtlActivity.this, url,
                                    getString(R.string.speech_service_name));
                        }
                    });
            dialog.show();
            return;
        }
        // 设置申请的语音菜谱应用appid
        SpeechUtility.getUtility(DtlActivity.this).setAppid(AppConstant.APP_ID);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 退出时释放连接
        speechSynthesizer.stopSpeaking(synthesizerListener);
        speechSynthesizer.destory();

        speechRecognizer.cancel(recognizerListener);
        speechRecognizer.destory();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 返回键
            // 退出时释放连接
            speechSynthesizer.stopSpeaking(synthesizerListener);
            speechSynthesizer.destory();

            speechRecognizer.cancel(recognizerListener);
            speechRecognizer.destory();
        }
        return true;
    }

    /**
     * 动态计算滚动条
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 如果服务组件没有安装，把服务组件apk安装包放在assets中，然后copy到SDcard中进行安装。
     */
    private void processInstall(Context context, String url, String assetsApk) {
        // 安装失败
        if (!ApkInstaller.installFromAssets(context, assetsApk)) {
            showTip(getString(R.string.install_fail));
        }
    }

    /**
     * 显示提示信息
     * 
     * @param str
     */
    private void showTip(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    /**
     * 语音合成监听器
     */
    private SynthesizerListener synthesizerListener = new SynthesizerListener.Stub() {
        @Override
        public void onBufferProgress(int progress) throws RemoteException {
        }

        /**
         * 步骤播完后如果还有其他步骤则播出提示音
         */
        @Override
        public void onCompleted(int code) throws RemoteException {
            if (1 == whichPlay) { // 步骤播放完毕后播放提示
                whichPlay = 2;
                tips = getString(R.string.step_tips);
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_TIP,
                        AppConstant.STEP_TIP_DELAY);
            } else if (2 == whichPlay) { // 提示播放完毕后开始识别语音命令
                if (isPause) {
                    isPause = false;
                }
                mPlayer = MediaPlayer.create(DtlActivity.this, R.raw.tip);

                mPlayer.setOnCompletionListener(new OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        whichPlay = 0;
                        mHandler.sendEmptyMessageDelayed(MessageType.RECOGNIZE,
                                AppConstant.TIP_REC_DELAY);
                        mPlayer.release();
                    }
                });
                mPlayer.setOnErrorListener(new OnErrorListener() {

                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        showTip("播放器错误:" + what + "," + extra);
                        return false;
                    }
                });

                if (mPlayer != null) {
                    mPlayer.stop();
                }
                try {
                    mPlayer.prepare();
                    mPlayer.start();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (3 == whichPlay) { // 全部播放完毕
                whichPlay = 0;
                stepNum = 0;
                tips = getString(R.string.step_tips);
                mHandler.sendEmptyMessage(MessageType.CHANGE_ICON_PLAY);
                speechSynthesizer.stopSpeaking(synthesizerListener);
                speechRecognizer.stopListening(recognizerListener);
            } else if (4 == whichPlay) {
                whichPlay = 2;
                tips = getString(R.string.tips_pause_over);
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_TIP,
                        pauseTimeValue);
            }
        }

        @Override
        public void onSpeakBegin() throws RemoteException {
            if (whichPlay == 0) {
                speechSynthesizer.stopSpeaking(synthesizerListener);
            }
        }

        @Override
        public void onSpeakPaused() throws RemoteException {
        }

        @Override
        public void onSpeakProgress(int progress) throws RemoteException {
        }

        @Override
        public void onSpeakResumed() throws RemoteException {
        }
    };

    /**
     * 语音识别监听器
     */
    private RecognizerListener recognizerListener = new RecognizerListener.Stub() {

        @Override
        public void onVolumeChanged(int v) throws RemoteException {
        }

        @Override
        public void onResult(final RecognizerResult result, boolean isLast)
                throws RemoteException {
            speechRecognizer.stopListening(recognizerListener);
            if (isPause || whichPlay != 0) {
                return;
            }
            String order = null;
            if (null != result) {
                order = JsonParser.parseIatResult(result.getResultString());
            }
            if (order == null || order.length() == 0 || order.matches("[。，？！]")) {
                return;
            }
            // 上一步
            if (order.matches(orderPrevStep)) {
                stepNum--;
                // 没有上一步
                if (stepNum < 0) {
                    stepNum++;
                    whichPlay = 2;
                    tips = getString(R.string.tips_prev_fail);
                    mHandler.sendEmptyMessageDelayed(
                            MessageType.SYNTHESIZE_TIP,
                            AppConstant.REC_STEP_DELAY);
                } else { // 播放上一步
                    whichPlay = 1;
                    tips = getString(R.string.step_tips);
                    mHandler.sendEmptyMessageDelayed(
                            MessageType.SYNTHESIZE_STEP,
                            AppConstant.REC_STEP_DELAY);
                }
            } else if (order.matches(orderNextStep)) {
                // 下一步
                stepNum++;
                if (stepNum < list.size()) {
                    whichPlay = 1;
                    tips = getString(R.string.step_tips);
                    mHandler.sendEmptyMessageDelayed(
                            MessageType.SYNTHESIZE_STEP,
                            AppConstant.REC_STEP_DELAY);
                } else {
                    whichPlay = 3;
                    tips = getString(R.string.tips_over);
                    mHandler.sendEmptyMessageDelayed(
                            MessageType.SYNTHESIZE_TIP,
                            AppConstant.REC_STEP_DELAY);
                }
            } else if (order.matches(orderPause)) {
                if (isPause) {
                    return;
                }
                Pattern pattern = Pattern
                        .compile(getString(R.string.order_pause_pattern));
                Matcher matcher = pattern.matcher(order);
                if (matcher.find()) {
                    String str1 = matcher.group(1);
                    pauseTimeValue = NumberUtils.numberCN2Arab(str1);
                    int temp = (int) pauseTimeValue;
                    String str2 = matcher.group(2);
                    if ("分钟".equals(str2)) {
                        pauseTimeValue = 1L * 1000 * 60 * pauseTimeValue;
                    } else {
                        if (0 == pauseTimeValue) {
                            pauseTimeValue = 5L;
                        }
                        pauseTimeValue = 1L * 1000 * pauseTimeValue;
                    }
                    pauseTimeStr = NumberUtils.numberArab2CN(temp) + str2;
                } else {
                    pauseTimeStr = "五秒";
                    pauseTimeValue = AppConstant.PAUSE_DELAY;
                }
                showTip(order);
                isPause = true;
                whichPlay = 4;
                tips = getString(R.string.tips_pause) + pauseTimeStr;
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_TIP,
                        AppConstant.REC_STEP_DELAY);

            } else if (order.matches(orderRePlay)) {
                whichPlay = 1;
                tips = getString(R.string.step_tips);
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_STEP,
                        AppConstant.REC_STEP_DELAY);
            } else {
                whichPlay = 2;
                tips = getString(R.string.recognize_no_order) + "：" + order
                        + "。" + "请重新输入";
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_TIP,
                        AppConstant.REC_STEP_DELAY);
            }
        }

        @Override
        public void onError(int errorCode) throws RemoteException {
            showTip("识别错误：" + errorCode);
            if (ErrorCode.SUCCESS != errorCode) {
                if (isPause || 0 != whichPlay) {
                    return;
                }
                whichPlay = 2;
                tips = getString(R.string.recognize_no_result);
                switch (errorCode) {
                case ErrorCode.ERROR_NO_NETWORK:
                    tips = "无有效的网络连接";
                    break;
                case ErrorCode.ERROR_NETWORK_TIMEOUT:
                    tips = "网络连接超时";
                    break;
                case ErrorCode.ERROR_NET_EXPECTION:
                    tips = "网络异常";
                    break;
                case ErrorCode.ERROR_INVALID_RESULT:
                    tips = "无有效的结果";
                    break;
                case ErrorCode.ERROR_NO_MATCH:
                    tips = "无匹配结果";
                    break;
                case ErrorCode.ERROR_AUDIO_RECORD:
                    tips = "录音失败";
                    break;
                case ErrorCode.ERROR_NO_SPPECH:
                    tips = "未检测到语音";
                    break;
                case ErrorCode.ERROR_SPEECH_TIMEOUT:
                    tips = "音频输入超时";
                    break;
                case ErrorCode.ERROR_INTERRUPT:
                    tips = "被异常打断";
                    break;
                case ErrorCode.ERROR_ENGINE_BUSY:
                    tips = "引擎繁忙";
                    break;
                case ErrorCode.ERROR_LOCAL_ENGINE:
                    tips = "本地引擎内部错误";
                    break;
                case ErrorCode.ERROR_IVW_INTERRUPT:
                    tips = "本地唤醒引擎被异常打断";
                    break;
                default:
                    break;
                }
                speechRecognizer.stopListening(recognizerListener);
                mHandler.sendEmptyMessageDelayed(MessageType.SYNTHESIZE_TIP,
                        AppConstant.REC_STEP_DELAY);
            }
        }

        @Override
        public void onEndOfSpeech() throws RemoteException {
        }

        @Override
        public void onBeginOfSpeech() throws RemoteException {
            showTip("开始录音");
            if (0 != whichPlay) {
                speechRecognizer.stopListening(recognizerListener);
            }
        }
    };
}
